package com.liuwei.spring.cloud.controller;

import com.liuwei.spring.cloud.biz.repository.db.entity.Users;
import com.liuwei.spring.cloud.biz.service.UsersService;
import com.liuwei.spring.cloud.biz.support.TraceHelper;
import com.liuwei.spring.cloud.framework.dto.Result;
import com.liuwei.spring.cloud.common.utils.Jackson;
import com.liuwei.spring.cloud.framework.spring.ApplicationHelper;
import io.micrometer.observation.annotation.Observed;
import io.micrometer.tracing.Tracer;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;
import java.util.concurrent.CompletableFuture;

/**
 * @author : MainController
 * @version V1.0
 * @date: 2023/12/23 12:19 AM
 * @Description: TODO
 */
@Slf4j
@RestController
@RequestMapping("/api/user")
@Tag(name = "User 表格数据")
@Observed(name = "User 表格数据")
public class UserController {

    @Resource
    UsersService iUsersService;

    @Resource
    Tracer tracer;

    @GetMapping("/byId")
    public Result<Users> getById(@RequestParam("id") int id){
        Users user = iUsersService.getUserByUid(id,"xliuwei");
        Map<String,String> baggage = TraceHelper.Micrometer.getBaggage();
        //baggage = tracer.getAllBaggage(tracer.currentSpan().context());
        baggage.put("name","liuwei");
        log.info("baggage:{}",Jackson.toJSONString(baggage));

        baggage= tracer.getAllBaggage();
        log.info("baggage:{}",Jackson.toJSONString(baggage));

        baggage= TraceHelper.Micrometer.getBaggage();
        log.info("baggage:{}",Jackson.toJSONString(baggage));

        /**
         * micrometer 跨线程无法获取 traceId
         */
        ThreadPoolTaskExecutor executor = (ThreadPoolTaskExecutor) ApplicationHelper.getBean("CompletableFuturePool");
        CompletableFuture.runAsync(new Runnable() {
            @Override
            public void run() {
                try {
                    String traceId = TraceHelper.Micrometer.traceId();
                    Map<String,String> baggage = TraceHelper.Micrometer.getBaggage();
                    log.info("CompletableFuture:{}{}",Jackson.toJSONString(baggage));
                } catch (Exception exception) {
                    log.error("系统全局异常信息发送失败",exception);
                }
            }
        },executor);
        return Result.success(user);
    }
}
